<template>
  <el-form>
    <el-form-item label="SPU名称 ">
      <el-input
        placeholder="请你输入SPU名称"
        v-model="productParams.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌 ">
      <el-select placeholder="请选择某一个品牌" v-model="productParams.tmId">
        <el-option
          v-for="(item, index) in allTradeMark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        >
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述 ">
      <el-input
        placeholder="请你输入SPU描述"
        type="textarea"
        v-model="productParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片 ">
      <el-upload
        v-model:file-list="spuImageList"
        action="/app-dev/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
     
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
    </el-form-item>
    <el-dialog v-model="dialogVisible">
      <img  :src="dialogImageUrl" alt="Preview Image"  style="display:block;width=200px;height:200px;margin:10px auto"/>
    </el-dialog>
    <el-form-item label="销售属性 ">
      <el-select
        :placeholder="
          unUseAtrrValue.length ? `还有${unUseAtrrValue.length}个选择` : `无`
        "
        v-model="unSaleAttrNameandId"
   
      >
        <el-option
          v-for="(item, index) in unUseAtrrValue"
          :key="index"
          :label="item.name"
          :value="`${item.id}:${item.name}`"
        >
        </el-option>
      </el-select>
      <el-button
        type="primary"
        :icon="Plus"
        style="margin: 0px 10px"
        :disabled="unSaleAttrNameandId.length? false : true"
        @click="addSaleAttr"
        >添加销售属性</el-button
      >
      <el-table
        style="margin: 10px 0px"
        border
        :data="spuSaleAttrList"
      >
        <el-table-column
          type="index"
          label="序号 "
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          label="销售属性名称 "
          width="160"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值名称 ">
          <template #="{ row, $index }">
            <el-tag style="margin: 5px 5px"
              closable
              :type="index % 2 == 0 ? 'success' : 'danger'"
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="index"
              @close="clearAttr(row, index)"
              >{{ item.saleAttrValueName }}</el-tag
            >

            <el-button v-if="!row.show" type="primary" :icon="Plus" size="small"  @click="addAttr(row)" ></el-button>

            <el-input v-else  :ref="(el) => (row.form = el)" @blur="toPlus(row)" v-model="row.inputValue"  size="small" style="width: 50px; diplay: inline-block" ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
           <el-button  type="danger" :icon="Delete"  size="small"  @click="deleteSaleAttr(row,$index)"></el-button>

        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        style="marign: 10px 10px"
        @click="addOrUpdateSpu"
        :disabled="spuSaleAttrList.length?false:true"
      >
        保存</el-button
      >
      <el-button @click="cancel"> 取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import {
  ref,
  defineEmits,
  defineExpose,
  reactive,
  nextTick,
  computed,
} from "vue";
import { Plus,Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";

import {
  reqAddOrUpdateSpu,
  reqBaseValueList,
  reqAllSaleAttr,
  reqImgList,
  reqAllTradeMark,
} from "../../../../api/product/spu/index";
import useCategory from "../../../../stores/category";

const useCategoryStore = useCategory();

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const PlusShow = ref(true);
const SaleAttrId = ref("");


const allSaleAttr = ref<any>([]);
const allTradeMark = ref<any>([]);
const productParams = ref<any>(
  {
  category3Id: "", //三级分类的ID,代表这个已有SPU归属于哪一个三级分类
  tmId: "", //收集品牌的ID
  spuName: "", //SPU名字
  description: "", //spu的描述
  spuImageList: [
    //携带照片墙的数据
  ],
  spuSaleAttrList: [
    //销售属性与属性值
  ],
});
const spuImageList = ref<any>([]);
const unSaleAttrNameandId = ref<any>("");
const spuSaleAttrList = ref<any>([]);
let unUseAtrrValue = computed(() => {
  let res = allSaleAttr.value.filter((item: any) => {
    return spuSaleAttrList.value.every((item1: any) => {
      return item.name != item1.saleAttrName;
    });
  });

  return res;
});



const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
const emit = defineEmits(["spuCancel"]);

// 发送4个请求获取全部参数展示
const sendFourRequest = async (row: any) => {
  Object.assign(productParams.value, row);

  let res1: any = await reqBaseValueList(row.id);
  let res2: any = await reqAllSaleAttr();
  let res3: any = await reqImgList(row.id);
  let imgList = res3.map((item: any) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    };
  });
  let res4: any = await reqAllTradeMark();
  allTradeMark.value = res4;
  spuImageList.value = imgList;
  spuSaleAttrList.value = res1.spuSaleAttrList;
  allSaleAttr.value = res2;
};
// addOrUpdateSpu 发送请求修改添加  整理参数

const addOrUpdateSpu = async () => {
  // 整理照片墙参数
  let sendImgParams=spuImageList.value.map((item:any)=>{
    return {
          imgName:item.name,
          imgUrl:item.response?item.response.data:item.url
        
    }
  })
 productParams.value.spuImageList=sendImgParams
 productParams.value.spuSaleAttrList=spuSaleAttrList.value
 
  

  
  await reqAddOrUpdateSpu(productParams.value);
  ElMessage({
    type: "success",
    message: productParams.value.id ? "修改成功" : "添加成功",
  });
  emit("spuCancel", {scene1:0,flag:productParams.value.id?'update':'add'});
};
const cancel = () => {
  emit("spuCancel", {scene1:0,flag:'update'});
};
// 点击tag X 触发的回调 删除属性值
const clearAttr = (row: any, index: number) => {
  row.spuSaleAttrValueList.splice(index, 1);
};
// 点击 + 增加属性值   并且给每个 row添加自身属性
const addAttr = (row: any) => {
  row.show = true;
  row.inputValue=''

  nextTick(() => {
    row.form.focus();
  });

 
};
// 转成 plus 按钮
const toPlus = (row: any) => {


    if(row.inputValue.trim()==''){
      ElMessage({
        type:'warning',
        message:'别是空的呀'
      })
      return
    }
    let repeat=row.spuSaleAttrValueList.find((item:any)=>item.saleAttrValueName==row.inputValue)
    if(repeat){
       ElMessage({
        type:'warning',
        message:'别重复涅'
       })
       return
    }
    row.show = false;
  row.spuSaleAttrValueList.push({
    baseSaleAttrId:row.baseSaleAttrId,
    saleAttrValueName: row.inputValue,
  });
};
//  添加sale属性
const addSaleAttr=()=>{
  // 整理属性对象属性向数组里面push
 let[baseSaleAttrId,saleAttrName]= unSaleAttrNameandId.value.split(':')
 let SaleAttrObj={
  baseSaleAttrId,
  saleAttrName,
  spuSaleAttrValueList:[]


 }

 
  spuSaleAttrList.value.push(SaleAttrObj)
  unSaleAttrNameandId.value=''
 
  
}
// 删除sale属性
const deleteSaleAttr=(row:any,index:any)=>{

  spuSaleAttrList.value.splice(index,1)

}
const clearParams= async(c3Id:string|number)=>{


  
  productParams.value=  {
  category3Id: c3Id, //三级分类的ID,代表这个已有SPU归属于哪一个三级分类
  tmId: "", //收集品牌的ID
  spuName: "", //SPU名字
  description: "", //spu的描述
  spuImageList: [
    //携带照片墙的数据
  ],
  spuSaleAttrList: [
    //销售属性与属性值
  ],
}


  

  
  let res2: any = await reqAllSaleAttr();
 let res4: any = await reqAllTradeMark();
 allTradeMark.value = res4;
 allSaleAttr.value = res2;
 spuImageList.value=[]
spuSaleAttrList.value=[]

 productParams.value.description=''
 productParams.value.spuName=''
 productParams.value.tmId='',
 productParams.value.id=''

 

}


defineExpose([sendFourRequest, productParams,clearParams]);
</script>

<style scoped></style>
